<template>
  <div>
    <Form ref="form" :rules="formValidate" :label-width="140" :model="form">
      <FormItem prop="image" :label-width="50"
        ><div style="width:100%;margin-bottom:10px;height:140px;">
          <Upload
            :headers="uploadHeader"
            :on-success="handleSuccess"
            :action="downloadFileUrl"
            ref="upload"
            type="drag"
            :format="['jpg', 'jpeg', 'png']"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            style="height:120px"
          >
            <img
              style="max-width:100%;max-height:140px"
              :src="form.image"
              v-if="form.image"
            />
            <div style="padding: 25px 0" v-else>
              <Icon
                type="ios-cloud-upload"
                size="52"
                style="color: #3399ff"
              ></Icon>
              <p>上传图片</p>
            </div>
          </Upload>
        </div></FormItem
      >
      <FormItem label="名称" prop="name">
        <Input v-model="form.name" />
      </FormItem>
      <FormItem label="滚阻系数特性" prop="rollingResistanceCoefficient">
        <InputNumber
          type="number"
          v-model.number="form.rollingResistanceCoefficient"
          style="width:100%"
        />
      </FormItem>
      <FormItem label="附着系数特性" prop="adhesionCoefficient">
        <InputNumber
          type="number"
          v-model.number="form.adhesionCoefficient"
          style="width:100%"
        />
      </FormItem>
      <Row class="code-row-bg" justify="end" type="flex" align="middle">
        其他人是否可见
        <i-switch v-model="form.isIndexShow" :true-value="1" :false-value="0" />
        其他人是否可用
        <i-switch v-model="form.otherCanUse" :true-value="1" :false-value="0" />
        <Button @click="cancel" style="margin-right:10px">取消</Button>
        <Button @click="save" type="primary">保存</Button>
      </Row>
    </Form>
  </div>
</template>
<script>
import { roadApi } from "@/api/road";
import { fileApi } from "@/api/file";
import Cookies from "js-cookie";
import { TOKEN_KEY } from "@/lib/cookie";
export default {
  name: "RoadListForm",
  components: {},
  props: {
    //是否为更新表单
    isUpdate: {
      type: Boolean,
      default: true
    },
    //更新的表单数据对象
    updateData: {
      type: Object
    }
  },
  data() {
    return {
      //表单数据
      form: {
        image: null,
        //名称
        name: null,
        //滚阻系数特性
        rollingResistanceCoefficient: null,
        //附着系数特性
        adhesionCoefficient: null,
        //创建人
        createUser: null,
        //更新人
        updateUser: null,
        isIndexShow: 1,
        otherCanUse: 1
      },
      //表单验证
      formValidate: {
        //名称
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        //滚阻系数特性
        rollingResistanceCoefficient: [
          {
            type: "number",
            required: true,
            message: "请输入滚阻系数特性",
            trigger: "blur"
          },
          {
            type: "number",
            min: 0,
            max: 1,
            message: "请输入0到1的数字",
            trigger: "blur"
          }
        ],
        //附着系数特性
        adhesionCoefficient: [
          {
            type: "number",
            required: true,
            message: "请输入附着系数特性",
            trigger: "blur"
          },
          {
            type: "number",
            min: 0,
            max: 2,
            message: "请输入0到2的数字",
            trigger: "blur"
          }
        ],
        //图片
        image: [{ required: true, message: "请上传图片", trigger: "blur" }]
      }
    };
  },
  watch: {
    updateData: function(newValue, oldValue) {
      this.$refs["form"].resetFields();
      if (this.isUpdate) {
        for (let k in this.form) {
          this.$set(this.form, k, newValue[k]);
        }
        this.$set(this.form, "id", newValue["id"]);
      }
    },
    isUpdate: function(newValue, oldValue) {
      if (!newValue) {
        this.resetForm();
        this.$refs["form"].resetFields();
      }
    },
    uploadHeader: function() {
      let header = {
        "x-access-token": Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function() {
      let baseUrl = fileApi.fileUploadLocalUrl;
      switch (this.searchForm.fileLocationType) {
        case 2:
          baseUrl = fileApi.fileUploadAliUrl;
          break;
        case 3:
          baseUrl = fileApi.fileUploadQiNiuUrl;
          break;
        default:
          break;
      }
      let url = baseUrl + this.searchForm.moduleType;
      return url;
    },
    // 文件业务类型
    moduleTypes: function() {
      let array = [];
      for (let item in SERVICE_TYPE) {
        let obj = {};
        obj.desc = SERVICE_TYPE[item].desc;
        obj.value = SERVICE_TYPE[item].value;
        array.push(obj);
      }
      return array;
    },
    fileLocationTypes: function() {
      let array = [];
      for (const item in FILE_TYPE) {
        let obj = {};
        obj.desc = FILE_TYPE[item].desc;
        obj.value = FILE_TYPE[item].value;
        array.push(obj);
      }
      return array;
    }
  },
  created() {
    this.downloadFileUrl = fileApi.fileUploadLocalUrl + "1";
  },
  mounted() {},
  methods: {
    beforeUpload() {
      this.$refs.upload.clearFiles();
    },
    handleSuccess(res, file) {
      console.log(file);
      console.log(res);

      this.form.image = res.data.url;
    },
    // 上传失败钩子
    uploadError(e) {
      this.$Message.error("上传出错，请重试！");
      console.error(e);
      this.find();
    },
    cancel() {
      this.resetForm();
      this.$emit("on-form-close");
    },
    save() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isUpdate) {
            this.update();
          } else {
            this.add();
          }
        } else {
          this.$Message.error("参数验证错误，请仔细填写表单数据!");
        }
      });
    },
    resetForm() {
      this.form = {
        image: null,
        //名称
        name: null,
        //滚阻系数特性
        rollingResistanceCoefficient: null,
        //附着系数特性
        adhesionCoefficient: null,
        //创建人
        createUser: null,
        //更新人
        updateUser: null,
        isIndexShow: 1,
        otherCanUse: 1
      };
      this.$refs["form"].resetFields();
    },
    async add() {
      this.$Spin.show();
      let res = await roadApi.addRoad(this.form);
      this.$Message.success(res.msg);
      this.$Spin.hide();
      this.resetForm();
      this.$emit("on-form-close");
    },
    async update() {
      this.$Spin.show();
      let res = await roadApi.updateRoad(this.form);
      this.$Message.success(res.msg);
      this.$Spin.hide();
      this.resetForm();
      this.$emit("on-form-close");
    }
  }
};
</script>
<style>
.tab-row {
  align-items: flex-start;
}
.ivu-switch {
  margin: 0 10px;
}
.ivu-upload {
  height: 140px;
}
</style>
